package com.crm.smartmachine.ui.common.adapter

import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.crm.smartmachine.R
import com.crm.smartmachine.bean.response.GoodsBean
import com.crm.smartmachine.bean.response.WPBean
import com.crm.smartmachine.contants.Constants

class ChooseGoodsAdapter : BaseQuickAdapter<WPBean, BaseViewHolder>(R.layout.item_choose_goods) {

    private var selectedPosition = -1
    private var lastPosition = -1

    override fun convert(holder: BaseViewHolder, item: WPBean) {
        item.apply {
            holder.setText(R.id.tvName, wpmc)
                .setText(R.id.tvSpec, ggxh)
                .setText(R.id.tvCount, "$count")
        }

        holder.itemView.isSelected = holder.layoutPosition == selectedPosition
        val checkIcon =
            if (holder.itemView.isSelected) R.drawable.icon_checkbox_checked else R.drawable.icon_checkbox_normal
        holder.setImageResource(R.id.ivCheckIcon, checkIcon)

        holder.itemView.setOnClickListener {
            holder.itemView.isSelected = true
            lastPosition = selectedPosition
            selectedPosition = holder.layoutPosition
            holder.setImageResource(R.id.ivCheckIcon, R.drawable.icon_checkbox_checked)
            notifyItemChanged(lastPosition)
        }
    }

    override fun onBindViewHolder(
        holder: BaseViewHolder,
        position: Int,
        payloads: MutableList<Any>
    ) {
        super.onBindViewHolder(holder, position, payloads)
        if (payloads.size > 0 && payloads[0] is Int) {
            val type = payloads[0] as Int
            val item = data[position]
            if (type == Constants.PAYLOAD_TV_GOODS_COUNT) {
                item.apply {
                    holder.setText(R.id.tvCount, "$count")
                }
            }
        }
    }

    interface OnSelectAllListener {
        fun onResult(all: Boolean)
    }

    fun getSelectedPosition(): Int {
        return selectedPosition
    }

    fun setSelectedPosition(position: Int) {
        selectedPosition = position
        notifyDataSetChanged()
    }

}